package com.globalresources.ui.servlet;

import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.acegisecurity.context.SecurityContextHolder;
import org.acegisecurity.userdetails.UserDetails;
import org.apache.log4j.Logger;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.globalresources.business.inface.IMessageService;
import com.globalresources.commons.Constant;
import com.globalresources.commons.StringHelper;



/**
 * @author aaron.lu(luzhiyuan) E-mail:atyuan.lu@gmail.com
 * @since 创建时间：Aug 10, 2009 9:41:03 AM
 */
public class AjaxServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	Logger logger = Logger.getLogger(this.getClass());
	
	private void processRequest(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{
		WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
		IMessageService messageService = (IMessageService)webApplicationContext.getBean("messageService");
		String current_username = getCurrentUerName();
		int news_count = 0;
		if (StringHelper.isNotEmpty(current_username)) {
			news_count = messageService.countMessageReceiver(current_username, Constant.BOOLEAN_FALSE, Constant.BOOLEAN_FALSE, Constant.BOOLEAN_FALSE, null);
		}else{
			logger.warn("No one login system!");
		}
		logger.info("Current User:" + current_username + "   New Message Count:" + news_count);
		String result = markupResult(news_count);
		response.setContentType("text/xml");
		response.getOutputStream().write(result.getBytes());
	}
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		processRequest(request, response);
	}
	
	/**
	 * <p>获取当前用户名字
	*@author aaron.lu(luzhiyuan)
	*@return
	 */
	private String getCurrentUerName(){
		String name = "";
		Object obj = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		if (null != obj && obj instanceof UserDetails){
			UserDetails userDetails = (UserDetails)obj;
			name = userDetails.getUsername();
		}
		return name;
	}
	
	/**
	 * 组装结果
	*@author aaron.lu(luzhiyuan)
	*@param news_count
	*@return
	 */
	private String markupResult(int news_count){
		StringBuffer sb = new StringBuffer("<news>");
		if (news_count == 0) {
			sb.append("<count>0</count>");
		}else {
			sb.append("<count>"+news_count+"</count>");
		}
		sb.append("</news>");
		return sb.toString();
	}
}
